﻿
EF.Trailblazers.Activity.VideoSequencing = EF.Trailblazers.Activity.VideoSequencing || {};
EF.Trailblazers.Activity.VideoSequencing = {
    "settings": { currentQuestion: 1, errorTimes: 0, QuestionCount: 0 },
    "models": {},
    "events": {},
    "handlers": {},
    "behaviors": {}
};

EF.Trailblazers.Activity.VideoSequencing.models = {
    "ActivityId": 10650,
    "ActivityType": "VideoSequencing",
    "CorrectAnswerCount": 4,
    "EndTime": "\/Date(1350337598000-0400)\/",
    "FrameworkType": "Standard",
    "MyCorrectAnswerCount": 1,
    "Score": 0,
    "StartTime": "\/Date(1350337577000-0400)\/",
    "StudentId": 14402700,
    "TimeElapsed": 21,
    "content": [
		{
		    "Answer": "5,,4,,2,1",
		    "CorrectAnswer": "1,2,3,4,5,6",
		    "Score": 50
		}, {
		    "Answer": ",,3,,1,6",
		    "CorrectAnswer": "1,2,3,4,5,6",
		    "Score": 50
		}, {
		    "Answer": ",4,3,2,1,",
		    "CorrectAnswer": "1,2,3,4,5,6",
		    "Score": 50
		}
	]
};

EF.Trailblazers.Activity.VideoSequencing.ready = function (data) {
    var models = EF.Trailblazers.Activity.VideoSequencing.models;
    var contentContainer = $("#act_container");

    EF.Trailblazers.Activity.VideoSequencing.behaviors._randomSequenceData(data);
    EF.Trailblazers.Activity.VideoSequencing.loadTemplate(contentContainer, data);
    EF.Trailblazers.Activity.VideoSequencing.events._register();
    EF.Trailblazers.Activity.VideoSequencing.handlers._bindModel(models);
};

EF.Trailblazers.Activity.VideoSequencing.submit = function () {
    var finished = EF.Trailblazers.Activity.VideoSequencing.checkFinish();
    console.log('finished: ' + finished);
    if (finished == false) {
        alert('finish Answer');
        return;
    }

    var hasErrorAnswer = EF.Trailblazers.Activity.VideoSequencing.checkError();
    console.log('hasError:' + hasErrorAnswer);
    if (hasErrorAnswer == true) {

    }

    var isLastQuestion

    console.log(EF.Trailblazers.Activity.VideoSequencing.models);
}

EF.Trailblazers.Activity.VideoSequencing.checkError = function () {
    var currentQuestion = EF.Trailblazers.Activity.VideoSequencing.settings.currentQuestion;
    var currentModel = EF.Trailblazers.Activity.VideoSequencing.models.content[currentQuestion];
    var correctAnswers = currentModel.CorrectAnswer.split(',');
    var hasErrorAnswer = false;
    $.each(currentModel.Answer.split(','), function (i) {
        if (this != correctAnswers[i]) {
            hasErrorAnswer = true;
        } else if (this == "") {
            console.log(this);
        }
    });

    return hasErrorAnswer;
};

EF.Trailblazers.Activity.VideoSequencing.checkFinish = function () {
    var currentQuestion = EF.Trailblazers.Activity.VideoSequencing.settings.currentQuestion;
    var models = EF.Trailblazers.Activity.VideoSequencing.models;
    var currentModel = models.content[currentQuestion];
    var Answerlength = 0;
    $.each(currentModel.Answer.split(','), function () {
        if (this != "") {
            Answerlength = Answerlength + 1;
        }
    })
    if (Answerlength != currentModel.CorrectAnswer.split(',').length) {
        return false;
    }
    return true;
};

EF.Trailblazers.Activity.VideoSequencing.showErrorAnswers = function () {
    var currentQuestion = EF.Trailblazers.Activity.VideoSequencing.settings.currentQuestion;
    var currentModel = EF.Trailblazers.Activity.VideoSequencing.models.content[currentQuestion];
    var correctAnswers = currentModel.CorrectAnswer.split(',');
    var $placeHolder = $(".act_sequen_placeholder");

    $.each(currentModel.Answer.split(','), function (i) {
        console.log(i);
        var currPlcaceHolder = $placeHolder.eq(i);
        if (this != correctAnswers[i] || this == "") {
            currPlcaceHolder.addClass("act_sequen_error");
        } else {
            currPlcaceHolder.removeClass("act_sequen_error");
        }
    });
};

EF.Trailblazers.Activity.VideoSequencing.progressManager = function () {

};

EF.Trailblazers.Activity.VideoSequencing.loadTemplate = function (contentContainer, data) {

    var url = "_templates/VideoSequencing.tpl";
    EF.Trailblazers.Activity.Common.loadTemplate(contentContainer, url, data, null, {
        filter_data: false
    }, {
        "name": "index",
        "value": EF.Trailblazers.Activity.VideoSequencing.settings.currentQuestion
    });
};

EF.Trailblazers.Activity.VideoSequencing.events._register = function () {

    var handlers = EF.Trailblazers.Activity.VideoSequencing.handlers;

    EF.Trailblazers.Activity.VideoSequencing.events._registeDropable();
    EF.Trailblazers.Activity.VideoSequencing.events._registeMouseUpDown("bind");
    EF.Trailblazers.Activity.VideoSequencing.events._registeSlide();

    $(document.body).disableSelection();
    $(".act_drag_box").hover(function () { $(this).css("cursor", "move"); });
    $(".btn_ok").click(function () {
        var result = EF.Trailblazers.Activity.VideoSequencing.check();
        if (result)
            EF.Trailblazers.Activity.VideoSequencing.submit();
    });
};

EF.Trailblazers.Activity.VideoSequencing.events._registeDropable = function () {

    var behaviors = EF.Trailblazers.Activity.VideoSequencing.behaviors;
    var handlers = EF.Trailblazers.Activity.VideoSequencing.handlers;

    $(".act_drag_box").draggable({
        revert: true,
        revertDuration: "300",
        containment: "act_content",
        zIndex: 101,
        stop: function (event, ui) {
            $(this).css({ "left": "0", "top": "0" });
            console.log("draggable stop: " + $(this).css("left") + " : " + $(this).css("top"));

            if (ui.helper.parent().hasClass("ui-droppable") == false) {
                var parent = $("#" + $(this).attr("parent"));
                var transform = parent.data("transform");

                behaviors._setTransform(parent, transform);
                $(this).find(".act_img_box").removeClass("act_img_box_drop_big_nomargin");

                parent.css({ "z-index": "auto" });
            }
        }
    });

    $(".act_sequen_placeholder").droppable({
        tolerance: "pointer",
        activeClass: "ui_state_active",
        hoverClass: "ui_state_hover",
        drop: function (event, ui) {
            var target = $(this).find(".act_drag_box");
            var drag = ui.helper;
            //change position drop
            if (target.attr("parent") != undefined && drag.attr("parent") != target.attr("parent")) {

                if (drag.hasClass("act_drag_box_big")) {
                    handlers._positionBtoS(drag, target);
                } else {
                    handlers._positionStoS(drag, target);
                }
            } else {
                //nomal drop
                var offset = behaviors._calcOffset(drag, $(this));
                drag.appendTo(this);
                drag.css(offset);
                drag
                    .removeClass("act_drag_box_big")
                    .addClass("act_drag_box_small");
                drag
                    .find(".act_img_box")
                    .removeClass("act_img_box_drop_big")
                    .addClass("act_img_box_drop_small");
                EF.Trailblazers.Activity.VideoSequencing.handlers._animateEaseOut(ui.draggable, 300);
            }
            // -- update model
            handlers._updateModel();
        }
    });

    $(".act_drag_container").droppable({
        tolerance: "pointer",
        drop: function (event, ui) {
            if (ui.draggable.parent().hasClass("act_sequen_placeholder") == false)
                return;

            var $parent = $("#" + ui.draggable.attr("parent"));
            var offset = behaviors._calcOffset(ui.draggable, $parent);
            ui.draggable.appendTo($parent);
            ui.draggable.css(offset);
            ui.draggable
                .removeClass("act_drag_box_small")
                .addClass("act_drag_box_big");
            ui.draggable.find(".act_img_box")
                .removeClass("act_img_box_drop_small")
                .addClass("act_img_box_drop_big");

            EF.Trailblazers.Activity.VideoSequencing.handlers._animateEaseOut(ui.draggable, 600);
            // --  update model
            handlers._updateModel();
        }
    });
};

EF.Trailblazers.Activity.VideoSequencing.events._registeMouseUpDown = (function () {

    var behaviors = EF.Trailblazers.Activity.VideoSequencing.behaviors;
    var handlers = EF.Trailblazers.Activity.VideoSequencing.handlers;

    var mousedownHandler = function () {
        var parent = $("#" + $(this).attr("parent"));

        if (parent.css('transform') != 'matrix(1, 0, 0, 1, 0, 0)') {
            parent.data("transform", parent.css('transform'));
            var transform = 'matrix(1, 0, 0, 1, 0, 0)';
            behaviors._setTransform(parent, transform);
        }

        if ($(this).parent().hasClass("act_sequen_placeholder")) {
            var transform = parent.data("transform");
            behaviors._setTransform(parent, transform);
        } else {
            $(this).find(".act_img_box").addClass("act_img_box_drop_big_nomargin");
        }

        parent.css({ "z-index": "100" });

    };

    var mouseupHandler = function () {
        var parent = $("#" + $(this).attr("parent"));
        var transform = parent.data("transform");

        behaviors._setTransform(parent, transform);
        $(this).find(".act_img_box").removeClass("act_img_box_drop_big_nomargin");

        parent.css({ "z-index": "auto" });
    }
    return function (event, elem) {
        if (elem === undefined) elem = $(".act_drag_box");
        if (event == "bind") {
            elem
            .bind("mouseup", mouseupHandler)
            .bind("mousedown", mousedownHandler);
        }
        if (event == "unbind") {
            elem
            .unbind("mouseup", mouseupHandler)
            .unbind("mousedown", mousedownHandler);
        }
    }
})();

EF.Trailblazers.Activity.VideoSequencing.events._registeSlide = function () {

    var settings = EF.Trailblazers.Activity.VideoSequencing.settings;
    //slide question
    $("div.act_radio_tab").bind("mouseover", function () {
        $(this).addClass("act_radio_tab_hover");
    }).bind("mouseout", function () {
        $(this).removeClass("act_radio_tab_hover");
    }).bind("click", function () {
        $("div.act_radio_tab").find("a").removeClass("act_radio_tab_active");
        $(this).find("a").addClass("act_radio_tab_active");

        var index = $("div.act_radio_tab").index(this);
        settings.currentQuestion = index;

        EF.Trailblazers.Activity.VideoSequencing.ready(jsonData);
    });
};

EF.Trailblazers.Activity.VideoSequencing.handlers._updateModel = function () {

    var currentQuestion = EF.Trailblazers.Activity.VideoSequencing.settings.currentQuestion;
    var _answerArr = [];
    $(".act_sequen_placeholder").each(function (i, n) {
        if ($(this).children().hasClass("act_drag_box")) {
            _answerArr[i] = $(this).find(".act_drag_box").attr("sequency");
        }
    });
    console.log(_answerArr.join(","));
    EF.Trailblazers.Activity.VideoSequencing.models
        .content[currentQuestion].Answer = _answerArr.join(",");
};

EF.Trailblazers.Activity.VideoSequencing.handlers._bindModel = function () {

    var settings = EF.Trailblazers.Activity.VideoSequencing.settings;
    var models = EF.Trailblazers.Activity.VideoSequencing.models;
    var answers = models.content[settings.currentQuestion].Answer.split(',');
    $(answers).each(function (i, n) {
        if (n !== "") {
            $(".act_drag_box").each(function () {
                if ($(this).attr("sequency") == n) {
                    var target = $(".act_sequen_placeholder:eq(" + i + ")");
                    EF.Trailblazers.Activity.VideoSequencing.handlers._positionBtoNull($(this), target);
                }
            });
        }
    });
};

EF.Trailblazers.Activity.VideoSequencing.handlers._showCorrectAnswer = function () {
    var settings = EF.Trailblazers.Activity.VideoSequencing.settings;
    var models = EF.Trailblazers.Activity.VideoSequencing.models;
    var answers = models.content[settings.currentQuestion].CorrectAnswer.split(',');
    $(answers).each(function (i, n) {
        var holder = $(".act_sequen_placeholder:eq(" + i + ")");
        //remove all drag
        if (holder.children().hasClass(".act_drag_box")) {
            var drag = holder.find(".act_drag_box");
            var target = $("#" + drag.atrr("parent"));
            EF.Trailblazers.Activity.VideoSequencing.handlers._positionStoNull(drag, target);
        }

        if (n !== "") {
            var drag = $(".act_drag_box").filter("[sequency=" + n + "]")
            if (drag.length != 0)
                EF.Trailblazers.Activity.VideoSequencing.handlers._positionBtoNull(drag, holder);
        }
    });
}

EF.Trailblazers.Activity.VideoSequencing.handlers._positionBtoNull = function (drag, target) {
    var _dragOffset = EF.Trailblazers.Activity.VideoSequencing.behaviors._calcOffset(drag, target);

    drag.appendTo(target);
    drag.css(_dragOffset);
    drag.removeClass("act_drag_box_big").addClass("act_drag_box_small"); ;
    drag.find(".act_img_box").removeClass("act_img_box_drop_big").addClass("act_img_box_drop_small");

    drag.animate({ "left": "0", "top": "0" }, 800);
}

EF.Trailblazers.Activity.VideoSequencing.handlers._positionStoNull = function (drag, target) {
    var _dragOffset = EF.Trailblazers.Activity.VideoSequencing.behaviors._calcOffset(drag, target);

    drag.appendTo(target);
    drag.css(_dragOffset);
    drag.removeClass("act_drag_box_small").addClass("act_drag_box_big"); ;
    drag.find(".act_img_box").removeClass("act_img_box_drop_small").addClass("act_img_box_drop_big");

    drag.animate({ "left": "0", "top": "0" }, 800);
}

EF.Trailblazers.Activity.VideoSequencing.handlers._positionStoS = function (drag, target) {
    var _dragOffset = EF.Trailblazers.Activity.VideoSequencing.behaviors._calcOffset(drag, target.parent());
    var _targetOffset = EF.Trailblazers.Activity.VideoSequencing.behaviors._calcOffset(target.parent(), drag.parent());
    var _tempDragParent = drag.parent();

    drag.appendTo(target.parent());
    target.appendTo(_tempDragParent);

    drag.css(_dragOffset);
    target.css(_targetOffset);

    EF.Trailblazers.Activity.VideoSequencing.handlers._animateEaseOut(drag, 600);
    EF.Trailblazers.Activity.VideoSequencing.handlers._animateEaseOut(target, 600);
}

EF.Trailblazers.Activity.VideoSequencing.handlers._positionBtoS = function (drag, target) {
    var _tempDragParent = $("#" + target.attr("parent"));

    var _dragOffset = EF.Trailblazers.Activity.VideoSequencing.behaviors._calcOffset(drag, target.parent());
    var _targetOffset = EF.Trailblazers.Activity.VideoSequencing.behaviors._calcOffset(target.parent(), _tempDragParent);

    drag.appendTo(target.parent());
    target.appendTo(_tempDragParent);

    drag.removeClass("act_drag_box_big").addClass("act_drag_box_small"); ;
    drag.find(".act_img_box").removeClass("act_img_box_drop_big").addClass("act_img_box_drop_small");

    target.removeClass("act_drag_box_small").addClass("act_drag_box_big"); ;
    target.find(".act_img_box").removeClass("act_img_box_drop_small").addClass("act_img_box_drop_big");

    drag.css(_dragOffset);
    target.css(_targetOffset);

    //    console.log("drag [left:" + drag.css("left") + " :top " + drag.css("top") + "]");
    //    console.log("target [left:" + target.css("left") + " :top " + target.css("top") + "]");

    //    console.log("dragoffset: " + _dragOffset.left + ":" + _dragOffset.top);
    //    console.log("targetOffset: " + _targetOffset.left + ":" + _targetOffset.top);

    EF.Trailblazers.Activity.VideoSequencing.handlers._animateEaseOut(drag, 600);
    EF.Trailblazers.Activity.VideoSequencing.handlers._animateEaseOut(target, 600);

    //    drag.animate({ "left": "0px", "top": "0px" }, { duration: 600, queue: false, easing: "easeOutBounce" });
    //    target.animate({ "left": "0px", "top": "0px" }, { duration: 600, queue: false, easing: "easeOutBounce" });
}

EF.Trailblazers.Activity.VideoSequencing.handlers._toggleTransform = function (dragElem, type) {
    var $parent = $("#" + dragElem.attr("parent"));
    var _transformCurrent = $parent.css("transform");
    var _transform = $parent.data("transform");

    if (type == "reset") {
        $parent.data("transform", _transformCurrent);
        _transform = "matrix(1, 0, 0, 1, 0, 0)";
    }
    EF.Trailblazers.Activity.VideoSequencing.behaviors._setTransform($parent, _transform)
}

EF.Trailblazers.Activity.VideoSequencing.handlers._animateEaseOut = function (elem, duration) {
    elem.animate({ "left": "0px", "top": "0px" }, { duration: duration, queue: false, easing: "easeOutBounce" });
};

EF.Trailblazers.Activity.VideoSequencing.behaviors._calcOffset = function (src, target) {
    return {
        "left": parseInt(src.offset().left - target.offset().left, 10) + "px",
        "top": parseInt(src.offset().top - target.offset().top, 10) + "px"
    }
}

EF.Trailblazers.Activity.VideoSequencing.behaviors._setTransform = function (elem, transform) {
    elem.css({ '-webkit-transform': transform });
    elem.css({ '-moz-transform': transform });
    elem.css({ '-ms-transform': transform });
    elem.css({ 'transform': transform });
}

EF.Trailblazers.Activity.VideoSequencing.behaviors._sort = function (array) {
    function randFunc() {
        return Math.random() >= 0.5 ? -1 : 1;
    }
    return array.sort(randFunc);
};

EF.Trailblazers.Activity.VideoSequencing.behaviors._randomSequenceData = function (data) {
    var behaviors = EF.Trailblazers.Activity.VideoSequencing.behaviors;
    $.each(data.Content.Questions, function (i, n) {
        n.Options = behaviors._sort(n.Options);
    });
}

EF.Trailblazers.Activity.VideoSequencing.behaviors._calcScore = function () {
    var score = 0;
    return score;
};